package 数据结构和算法.算法.查找算法.二分查找;

/**
 * 前提是查找的数组是有序的
 */
public class Test {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8};
        System.out.printf(String.valueOf(search(array, 0, array.length - 1, 10)));
        System.out.printf(String.valueOf(search2(array, 0, array.length - 1, 10)));
    }

    public static boolean search(int[] array, int L, int R, int key) {
        int middle = L + (R - L) / 2; //怕high+low溢出，采用这个写法
        if (L > R) {
            return false;
        }
        if (key == array[middle]) {
            return true;
        }
        if (array[middle] < key) {
            return search(array, middle + 1, R, key);
        }
        if (array[middle] > key) {
            return search(array, L, middle - 1, key);
        }

        return false;

    }

    public static boolean search2(int[] array, int L, int R, int key) {
        int i = L;
        int j = R;
        while (i <= j) {
            int middle = i + (j - i) / 2;
            if (key < array[middle]) {
                j = middle - 1;
            } else if (key > array[middle]) {
                i = middle + 1;
            } else {
                return true;
            }
        }

        return false;
    }
}
